package com.psa.element;

import android.content.ContentValues;
import android.database.Cursor;
import com.google.gson.Gson;
import com.psa.tool.DBTool;

/**
 *
 * @author david
 * @date 2016-07-26
 */
public class MerchandisePrice implements IJson,ISqlObject{
    public String ProdCode = "";
    public String CustCode = "";
    public String PriceType = "";
    public int PriceLevel = 0;
    public float Price =0.0f;

    @Override
    public String toJson() {
        return new Gson().toJson(this);
    }

    @Override
    public int insert(DBTool dbTool) {
        ContentValues values = new ContentValues();
        values.put("ProdCode", ProdCode.trim());
        values.put("CustCode", CustCode.trim());
        values.put("PriceType", PriceType.trim());
        values.put("PriceLevel", PriceLevel);
        values.put("Price", Price);
        return (int)dbTool.insert("MerchandisePrice", values);
    }

    @Override
    public int update(DBTool dbTool) {
        return 0;
    }

    @Override
    public int delete(DBTool dbTool) {
        return 0;
    }

    @Override
    public ISqlObject full(Cursor cursor) {
        if (cursor!=null && cursor.moveToNext()) {
            MerchandisePrice merchandisePrice = new MerchandisePrice();
            merchandisePrice.ProdCode = cursor.getString(0).trim();
            merchandisePrice.CustCode = cursor.getString(1);
            merchandisePrice.PriceType = cursor.getString(2);
            merchandisePrice.PriceLevel = cursor.getInt(3);
            merchandisePrice.Price = cursor.getFloat(4);
            return merchandisePrice;
        }
        return null;
    }

    @Override
    public void clear(DBTool dbTool) {
        dbTool.delete("MerchandisePrice", "ProdCode Like ?", new String[]{"%"});
    }

    @Override
    public String getDataSql() {
        return "MerchandisePrice";
    }

    @Override
    public String getSyncMethod() {
        return "getdataobjects";
    }

    public static float getPrice(String custCode, String prodCode, String priceType) {
        Cursor cursor = DBTool.getInstance().query("Select Price From MerchandisePrice Where ProdCode='"+prodCode+"' And CustCode='"+custCode+"'");
        if (cursor!=null && cursor.moveToNext()) {
            return cursor.getFloat(0);
        } else {
            cursor = DBTool.getInstance().query("Select Price From MerchandisePrice Where ProdCode='"+prodCode+"' And CustCode='~' And PriceType='"+priceType+"'");
            if (cursor!=null && cursor.moveToNext()) {
                return cursor.getFloat(0);
            } else {
                return 1;
            }
        }
    }
}
